package com.idc.resource.help;

import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import com.idc.resource.help.model.EmailConfig;
import com.idc.resource.help.model.EmailMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件
 * Created by Administrator on 2017/7/15 0015.
 */
@Slf4j
@Component
public class EmailHelp {
    /** 邮箱配置信息 */
    @Autowired
    private EmailConfig emailConfig;

    /**
     * 创建邮件
     * @param session 会话
     * @param receiveMailMsg 收件人信息及邮件内容
     * @return 邮件
     */
    private MimeMessage createMimeMessage(Session session,  EmailMsg receiveMailMsg) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);
        // 2. From: 发件人
        message.setFrom(new InternetAddress(emailConfig.getSendMail(), emailConfig.getSendName(), emailConfig.getCharSet()));
        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailMsg.getReceiverMail(), receiveMailMsg.getReceiverName(), "UTF-8"));
        // 4. Subject: 邮件主题
        message.setSubject(receiveMailMsg.getMainTitle(), emailConfig.getCharSet());
        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(receiveMailMsg.getMsg(), "text/html;charset="+emailConfig.getCharSet());
        // 6. 设置发件时间
        message.setSentDate(new Date());
        // 7. 保存设置
        message.saveChanges();
        return message;
    }

    private Session createSession(Authenticator authenticator){
        log.info("邮件配置:{}",emailConfig);
        Properties props = new Properties();                    // 参数配置
        // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.transport.protocol", emailConfig.getProtocol());
        // 发件人的邮箱的服务器地址
        props.setProperty("mail.smtp.host", emailConfig.getHost());
        // 需要请求认证
        props.setProperty("mail.smtp.auth",emailConfig.getAuth());
        //邮箱端口
        props.setProperty("mail.smtp.port", emailConfig.getPort());
        //是否有ssl认证要求
        if(emailConfig.getSsl()) {
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", emailConfig.getPort());
        }
        Session session = Session.getDefaultInstance(props,authenticator);
        if(emailConfig.getEmailDebugLog()) {
            session.setDebug(true);
        }
        return session;
    }

    /**
     * 发送邮件
     * @param emailMsg 需要发送的邮件信息
     * @return true 发送成功 false 发送失败
     */
    public boolean sendEmail(EmailMsg emailMsg){
        try {
            //创建认证信息
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = emailConfig.getSendUser();
                    String password = emailConfig.getSendPwd();
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = createSession(authenticator);
            // 创建邮件消息
            MimeMessage message = createMimeMessage(mailSession,emailMsg);
            // 发送邮件
            Transport.send(message);
            return true;
        }catch (Exception e){
            log.error("邮件发送失败，系统异常：",e);
            throw new IdcServiceException(ErrorCodeEnum.SYSTEM_ERROR.getCode(),ErrorCodeEnum.SYSTEM_ERROR.getDesc());
        }
    }

    public String buildMsgByTemp(Map<String,String> paramMap){
        String tempStr = emailConfig.getMsgTemp();
        for (String key:paramMap.keySet()){
            tempStr = tempStr.replaceAll("@"+key,paramMap.get(key));
        }
        return tempStr;
    }
}
